<template>
  <div class="contract-detail">
    <template v-if="isDataResult">
        <!-- 房源信息 -->
        <div class="title">房源信息</div>
        <div class="form">

          <!-- 地址 -->
          <div class="form-item">
            <picker
              v-if="actionKey === 'add'"
              :range="houseData"
              :value="houseDataPicker"
              @change="houseDataChange">
              <CustomInput
                title="地址"
                placeholder="请选择房源信息"
                :value="formItem.roomAddress" />
            </picker>
            <CustomInput
              v-else
              title="地址"
              placeholder="请选择房源信息"
              :value="formItem.roomAddress" />
          </div>
          <!-- 房号 -->
          <div class="form-item">
            <picker
              v-if="actionKey === 'add'"
              :range="houseData"
              :value="houseDataPicker"
              @change="houseDataChange">
              <CustomInput
                title="房号"
                placeholder="请选择房源信息"
                :value="formItem.roomNo" />
            </picker>
            <CustomInput
              v-else
              title="房号"
              placeholder="请选择房源信息"
              :value="formItem.roomNo" />
          </div>
          <!-- 入住日期 -->
          <div class="form-item">
            <picker
              v-if="!isRead"
              mode="date"
              start="1900-01-01"
              end="2030-12-31"
              :value="formItem.checkInDate"
              @change="checkInDateChange">
              <CustomInput
                title="入住日期"
                placeholder="请选择入住日期"
                :value="formItem.checkInDate" />
            </picker>
            <CustomInput
              v-else
              title="入住日期"
              placeholder="请选择入住日期"
              :value="formItem.checkInDate" />
          </div>
          <!-- 到期日期 -->
          <div class="form-item">
            <picker
              v-if="!isRead"
              mode="date"
              start="1900-01-01"
              end="2030-12-31"
              :value="formItem.checkOutDate"
              @change="checkOutDateChange">
              <CustomInput
                title="到期日期"
                placeholder="请选择到期日期"
                :value="formItem.checkOutDate" />
            </picker>
            <CustomInput
              v-else
              title="到期日期"
              placeholder="请选择到期日期"
              :value="formItem.checkOutDate" />
          </div>
          <!-- 结算 -->
          <div class="form-item">
            <CustomInput
              v-model="formItem.rentSettle"
              inputType="number"
              title="结算"
              company="个月"
              placeholder="请输入结算"
              :isInput="!isRead" />
          </div>
          <!-- 收租日 -->
          <div class="form-item">
            <CustomInput
              v-model="formItem.rentMoneyDate"
              inputType="number"
              title="收租日"
              company="号"
              placeholder="请输入收租日"
              :isInput="!isRead" />
          </div>
        </div>

        <!-- 租客信息 -->
        <div class="title clear">
          <div class="pull-left">租客信息</div>
          <div v-if="!isRead" class="pull-right" @tap="addContract">添加租客</div>
        </div>
        <div class="form">
          <!-- 名称 -->
          <div class="form-item">
            <picker
              v-if="!isRead"
              :range="rentorNameData"
              :value="rentorName"
              @change="rentorNameChange">
              <CustomInput
                title="名称"
                placeholder="请选择租客信息"
                :value="formItem.rentorName" />
            </picker>
            <CustomInput
              v-else
              title="名称"
              placeholder="请选择租客信息"
              :value="formItem.rentorName" />
          </div>
          <!-- 证件号 -->
          <div class="form-item">
            <picker
              v-if="!isRead"
              :range="rentorNameData"
              :value="rentorName"
              @change="rentorNameChange">
              <CustomInput
                title="证件号"
                placeholder="请选择租客信息"
                :value="formItem.idcards" />
            </picker>
            <CustomInput
              v-else
              title="证件号"
              placeholder="请选择租客信息"
              :value="formItem.idcards" />
          </div>
          <!-- 联系电话 -->
          <div class="form-item">
            <picker
              v-if="!isRead"
              :range="rentorNameData"
              :value="rentorName"
              @change="rentorNameChange">
              <CustomInput
                title="联系电话"
                placeholder="请选择租客信息"
                :value="formItem.rentorPhone" />
            </picker>
            <CustomInput
              v-else
              title="联系电话"
              placeholder="请选择租客信息"
              :value="formItem.rentorPhone" />
          </div>
        </div>

        <!-- 水费 -->
        <div class="title">水费</div>
        <div class="form">
          <!-- 水价 -->
          <div class="form-item">
            <CustomInput
              v-model="formItem.waterPrice"
              inputType="number"
              title="水价"
              company="元/吨"
              placeholder="请输入水价"
              :isInput="!isRead" />
          </div>
          <!-- 水表值 -->
          <div class="form-item">
            <CustomInput
              v-model="formItem.waterNowUsed"
              inputType="number"
              title="水表值"
              company="吨"
              placeholder="请输入水表值"
              :isInput="!isRead" />
          </div>
        </div>

        <!-- 电费 -->
        <div class="title">电费</div>
        <div class="form">
          <!-- 电价 -->
          <div class="form-item">
            <CustomInput
              v-model="formItem.electricPrice"
              inputType="number"
              title="电价"
              company="元/度"
              placeholder="请输入电价"
              :isInput="!isRead" />
          </div>
          <!-- 电表值 -->
          <div class="form-item">
            <CustomInput
              v-model="formItem.electricNowUsed"
              inputType="number"
              title="电表值"
              company="度"
              placeholder="请输入电表值"
              :isInput="!isRead" />
          </div>
        </div>

        <!-- 燃气费 -->
        <div class="title">燃气费</div>
        <div class="form">
          <!-- 燃气价 -->
          <div class="form-item">
            <CustomInput
              v-model="formItem.gasPrice"
              inputType="number"
              title="燃气价"
              company="元/方"
              placeholder="请输入燃气价"
              :isInput="!isRead" />
          </div>
          <!-- 燃气值 -->
          <div class="form-item">
            <CustomInput
              v-model="formItem.gasNowUsed"
              inputType="number"
              title="燃气值"
              company="方"
              placeholder="请输入燃气值"
              :isInput="!isRead" />
          </div>
        </div>

        <!-- 费用详情 -->
        <div class="title">费用详情</div>
        <div class="form">
          <!-- 租金 -->
          <div class="form-item">
            <CustomInput
              v-model="formItem.rentMoney"
              inputType="number"
              title="租金"
              placeholder="请输入租金"
              :isInput="!isRead" />
          </div>
          <!-- 租房押金 -->
          <div class="form-item">
            <CustomInput
              v-model="formItem.rentDespoit"
              inputType="number"
              title="租房押金"
              placeholder="请输入租房押金"
              :isInput="!isRead" />
          </div>
          <!-- 电费押金 -->
          <div class="form-item">
            <CustomInput
              v-model="formItem.electricDespoit"
              inputType="number"
              title="电费押金"
              placeholder="请输入电费押金"
              :isInput="!isRead" />
          </div>
          <!-- 水费押金 -->
          <div class="form-item">
            <CustomInput
              v-model="formItem.waterDespoit"
              inputType="number"
              title="水费押金"
              placeholder="请输入水费押金"
              :isInput="!isRead" />
          </div>
          <!-- 钥匙数量 -->
          <div class="form-item">
            <CustomInput
              v-model="formItem.keyCount"
              inputType="number"
              title="钥匙数量"
              placeholder="请输入钥匙数量"
              :isInput="!isRead" />
          </div>
          <!-- 钥匙押金 -->
          <div class="form-item">
            <CustomInput
              v-model="formItem.keyDespoit"
              inputType="number"
              title="钥匙押金"
              placeholder="请输入钥匙押金"
              :isInput="!isRead" />
          </div>
          <!-- 门卡数量 -->
          <div class="form-item">
            <CustomInput
              v-model="formItem.doorCardCount"
              inputType="number"
              title="门卡数量"
              placeholder="请输入门卡数量"
              :isInput="!isRead" />
          </div>
          <!-- 门卡押金 -->
          <div class="form-item">
            <CustomInput
              v-model="formItem.doorCardDespoit"
              inputType="number"
              title="门卡押金"
              placeholder="请输入门卡押金"
              :isInput="!isRead" />
          </div>
          <!-- 管理费 -->
          <div class="form-item">
            <CustomInput
              v-model="formItem.manageMoney"
              inputType="number"
              title="管理费"
              placeholder="请输入管理费"
              :isInput="!isRead" />
          </div>
          <!-- 卫生费 -->
          <div class="form-item">
            <CustomInput
              v-model="formItem.hygieneMoney"
              inputType="number"
              title="卫生费"
              placeholder="请输入卫生费"
              :isInput="!isRead" />
          </div>
          <!-- 网费 -->
          <div class="form-item">
            <CustomInput
              v-model="formItem.netMoney"
              inputType="number"
              title="网费"
              placeholder="请输入网费"
              :isInput="!isRead" />
          </div>
          <!-- 电视费 -->
          <div class="form-item">
            <CustomInput
              v-model="formItem.tvMoney"
              inputType="number"
              title="电视费"
              placeholder="请输入电视费"
              :isInput="!isRead" />
          </div>
          <!-- 电梯费 -->
          <div class="form-item">
            <CustomInput
              v-model="formItem.giftMoney"
              inputType="number"
              title="电梯费"
              placeholder="请输入电梯费"
              :isInput="!isRead" />
          </div>
          <!-- 其他 -->
          <div class="form-item">
            <CustomInput
              v-model="formItem.otherMoney"
              inputType="number"
              title="其他"
              placeholder="请输入其他"
              :isInput="!isRead" />
          </div>
        </div>

        <!-- 模版 -->
        <div class="title">模版</div>
        <div class="form">
          <!-- 合同模版 -->
          <div class="form-item">
            <picker
              v-if="!isRead"
              :range="contractIdData"
              :value="contractId"
              @change="contractIdChange">
              <CustomInput
                title="合同模版"
                placeholder="请选择合同模版"
                :value="formItem.__custom_contractId" />
            </picker>
            <CustomInput
              v-else
              title="合同模版"
              placeholder="合同模版"
              :value="formItem.__custom_contractId" />
          </div>
        </div>

        <!-- 保存按钮 -->
        <div v-if="!isRead" class="action">
          <i-button type="primary" @click="actionClick">保存</i-button>
        </div>
    </template>
  </div>
</template>

<script>
import CustomInput from 'components/CustomInput/CustomInput'
import { mapState, mapMutations } from 'vuex'
import { ERR_OK } from 'api/config'
import { saveData, getPerson, getHouse, getTemplate } from 'api/contractDetail'
import { shareMixin } from 'common/js/mixins'

export default {
  mixins: [shareMixin()],
  components: {
    CustomInput
  },
  computed: {
    isRead () {
      return this.actionKey === 'read'
    },
    houseData () {
      if (this.houseAllData.length === 0) {
        return []
      }

      const arr = []

      this.houseAllData.map(item => {
        arr.push(item.roomNo)
      })

      return arr
    },
    rentorNameData () {
      if (this.rentorNameAllData.length === 0) {
        return []
      }

      const arr = []

      this.rentorNameAllData.map(item => {
        arr.push(item.rentorName)
      })

      return arr
    },
    contractIdData () {
      if (this.contractIdAllData.length === 0) {
        return []
      }

      const arr = []

      this.contractIdAllData.map(item => {
        arr.push(item.htName)
      })

      return arr
    },
    ...mapState({
      titleKey: state => state.contract.titleKey,
      currentItem: state => state.contractDetail.currentItem,
      actionKey: state => state.contractDetail.actionKey
    })
  },
  onShow () {
    this.isRefreshPerson()
  },
  mounted () {
    this.initTitle()
    this.initData()
  },
  data () {
    return {
      isDataResult: false,
      formItem: {},
      houseDataPicker: 0,
      houseAllData: [],
      rentorName: 0,
      rentorNameAllData: [],
      contractId: 0,
      contractIdAllData: []
    }
  },
  methods: {
    async initData () {
      await this.getListData()

      if (this.actionKey === 'edit' || this.actionKey === 'read') {
        this.formItem = JSON.parse(JSON.stringify(this.currentItem))

        this.rentorName = this.rentorNameData.findIndex(item => item === this.formItem.rentorName)
        const contractItem = this.contractIdAllData.find(item => item.id === this.formItem.contractId)
        this.contractId = this.contractIdAllData.findIndex(item => item.id === this.formItem.contractId)

        this.formItem.__custom_contractId = contractItem.htName
      } else if (this.actionKey === 'addEdit') {
        this.formItem = JSON.parse(JSON.stringify(this.currentItem))
        this.$set(this.formItem, 'rentDespoit', 0)
        this.$set(this.formItem, 'electricDespoit', 0)
        this.$set(this.formItem, 'waterDespoit', 0)
        this.$set(this.formItem, 'keyCount', 0)
        this.$set(this.formItem, 'keyDespoit', 0)
        this.$set(this.formItem, 'doorCardCount', 0)
        this.$set(this.formItem, 'doorCardDespoit', 0)

        this.rentorName = this.rentorNameData.findIndex(item => item === this.formItem.rentorName)
        const contractItem = this.contractIdAllData.find(item => item.id === this.formItem.contractId)
        this.contractId = this.contractIdAllData.findIndex(item => item.id === this.formItem.contractId)
        this.formItem.__custom_contractId = contractItem.htName
      } else {
        this.houseDataPicker = 0
        this.rentorName = 0
        this.contractId = 0

        this.formItem = {
          roomAddress: '',
          roomNo: '',
          checkInDate: '',
          checkOutDate: '',
          rentSettle: 1,
          rentMoneyDate: 1,
          waterPrice: 0,
          waterNowUsed: 0,
          electricPrice: 0,
          electricNowUsed: 0,
          gasPrice: 0,
          gasNowUsed: 0,
          rentMoney: 0,
          rentDespoit: 0,
          electricDespoit: 0,
          waterDespoit: 0,
          keyCount: null,
          keyDespoit: 0,
          doorCardCount: 0,
          doorCardDespoit: 0,
          manageMoney: 0,
          hygieneMoney: 0,
          netMoney: 0,
          tvMoney: 0,
          giftMoney: 0,
          otherMoney: 0,
          contractId: 0,
          __custom_contractId: ''
        }
      }
    },
    isRefreshPerson () {
      if (this.isNeedRefreshPerson) {
        this.getPerson()
        this.isNeedRefreshPerson = false
      }
    },
    addContract () {
      this.isNeedRefreshPerson = true
      this.SET_ACTIONKEY('add')
      wx.navigateTo({
        url: '/pages/tenantDetail/main'
      })
    },
    actionClick () {
      const obj = JSON.parse(JSON.stringify(this.formItem))

      this.deleteCustomKey(obj)

      if (this.actionKey === 'addEdit') {
        delete obj.id
        obj.roomId = this.currentItem.id
      }

      this.saveData(obj)
    },
    deleteCustomKey (obj) {
      for (let key in obj) {
        if (key.indexOf('__custom_') > -1 || obj[key] === null) {
          delete obj[key]
        }
      }
    },
    contractIdChange (e) {
      this.contractId = e.target.value
      this.formItem.contractId = this.contractIdAllData[this.contractId].id
      this.formItem.__custom_contractId = this.contractIdAllData[this.contractId].htName
    },
    otherMoneyChange (e) {
      this.formItem.otherMoney = e.target.detail.value
    },
    giftMoneyChange (e) {
      this.formItem.giftMoney = e.target.detail.value
    },
    tvMoneyChange (e) {
      this.formItem.tvMoney = e.target.detail.value
    },
    netMoneyChange (e) {
      this.formItem.netMoney = e.target.detail.value
    },
    hygieneMoneyChange (e) {
      this.formItem.hygieneMoney = e.target.detail.value
    },
    manageMoneyChange (e) {
      this.formItem.manageMoney = e.target.detail.value
    },
    rentMoneyChange (e) {
      this.formItem.rentMoney = e.target.detail.value
    },
    doorCardDespoitChange (e) {
      this.formItem.doorCardDespoit = e.target.detail.value
    },
    doorCardCountChange (e) {
      this.formItem.doorCardCount = e.target.detail.value
    },
    keyDespoitChange (e) {
      this.formItem.keyDespoit = e.target.detail.value
    },
    keyCountChange (e) {
      this.formItem.keyCount = e.target.detail.value
    },
    waterDespoitChange (e) {
      this.formItem.waterDespoit = e.target.detail.value
    },
    electricDespoitChange (e) {
      this.formItem.electricDespoit = e.target.detail.value
    },
    rentDespoitChange (e) {
      this.formItem.rentDespoit = e.target.detail.value
    },
    gasNowUsedChange (e) {
      this.formItem.gasNowUsed = e.target.detail.value
    },
    gasPriceChange (e) {
      this.formItem.gasPrice = e.target.detail.value
    },
    electricNowUsedChange (e) {
      this.formItem.electricNowUsed = e.target.detail.value
    },
    electricPriceChange (e) {
      this.formItem.electricPrice = e.target.detail.value
    },
    waterNowUsedChange (e) {
      this.formItem.waterNowUsed = e.target.detail.value
    },
    waterPriceChange (e) {
      this.formItem.waterPrice = e.target.detail.value
    },
    rentorNameChange (e) {
      this.rentorName = e.target.value
      this.formItem.rentorName = this.rentorNameData[this.rentorName]
      this.formItem.rentorId = this.rentorNameAllData[this.rentorName].id
      this.formItem.idcards = this.rentorNameAllData[this.rentorName].idcards
      this.formItem.rentorPhone = this.rentorNameAllData[this.rentorName].rentorPhone
    },
    rentMoneyDateChange (e) {
      this.formItem.rentMoneyDate = e.target.detail.value
    },
    rentSettleChange (e) {
      this.formItem.rentSettle = e.target.detail.value
    },
    checkOutDateChange (e) {
      this.formItem.checkOutDate = e.target.value
    },
    checkInDateChange (e) {
      this.formItem.checkInDate = e.target.value
    },
    houseDataChange (e) {
      this.houseDataPicker = e.target.value
      this.formItem.roomNo = this.houseAllData[this.houseDataPicker].roomNo
      this.formItem.roomAddress = this.houseAllData[this.houseDataPicker].roomAddress
    },
    initTitle () {
      wx.setNavigationBarTitle({
        title: `${this.titleKey}详情`
      })
    },
    getListData () {
      return new Promise(async (resolve, reject) => {
        this.isDataResult = false
        this.$showLoading('加载中')

        const res = await Promise.all([getHouse(), getPerson(), getTemplate()])

        this.isDataResult = true
        this.$hideLoading()

        if (res[0].code === ERR_OK) {
          this.houseAllData = res[0].rows
        }

        if (res[1].code === ERR_OK) {
          this.rentorNameAllData = res[1].rows
        }

        if (res[2].code === ERR_OK) {
          this.contractIdAllData = res[2].rows
        }

        resolve()
      })
    },
    async saveData (data) {
      this.$showLoading('保存中')

      const res = await saveData(data)

      this.$hideLoading()

      if (res.code === ERR_OK) {
        this.$showToast({
          title: '保存成功',
          success: () => {
            wx.navigateBack()
          }
        })
      } else {
        this.$showToast({
          title: (res && res.msg) || '保存失败',
          icon: 'none'
        })
      }
    },
    async getPerson () {
      const res = await getPerson()

      if (res.code === ERR_OK) {
        this.rentorNameAllData = res.rows
      }
    },
    ...mapMutations({
      SET_ACTIONKEY: 'tenantDetail/SET_ACTIONKEY'
    })
  }
}
</script>

<style lang="scss" scoped>
  .contract-detail {
    width: 100%;
    overflow-x: hidden;
    > .title {
      width: 100%;
      line-height: 40px;
      background-color: rgb(248, 248, 248);
      font-size: 14px;
      padding: 0 10px;
      box-sizing: border-box;
    }
    > .form {
      > .form-item {
        border-bottom: 1px solid rgb(238, 238, 238);
      }
    }
  }
</style>
